import 'package:fish_redux/fish_redux.dart';
import '../../../app_files.dart';
import 'action.dart';
import 'state.dart';
import 'dart:convert';
import 'dart:io';
import '../model/normal_config_model.dart';
import 'dart:convert' as convert;

Effect<EngineerGasOpenViewState> buildEffect() {
  return combineEffects(<Object, Effect<EngineerGasOpenViewState>>{
    EngineerGasOpenViewAction.onTap: _onTap,
    EngineerGasOpenViewAction.onTapAddPic: _onTapAddPic,
    EngineerGasOpenViewAction.onTapPic: _onTapPic,
    EngineerGasOpenViewAction.onSubmit: _onSubmit,
    Lifecycle.initState: _initState,
  });
}

void _onTap(Action action, Context<EngineerGasOpenViewState> ctx) async {
  String type = action.payload['type'];
  if (type == 'refresh') {
    ctx.dispatch(EngineerGasOpenViewActionCreator.onAction());
  }
  if (type == 'onAddPic') {
    NormalConfigModel model = action.payload['model'];
    AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(
        ctx.context,
        type: 2,
        info: ctx.state.model);
    if (imgFile != null) {
      model.imageList.add(imgFile);
      ctx.dispatch(EngineerGasOpenViewActionCreator.onAction());
    }
  }
  if (type == 'onTapPic') {
    NormalConfigModel model = action.payload['model'];
    var file = action.payload['file'];
    int res =
        await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
    if (res == 1) {
      model.imageList.remove(file);
      ctx.dispatch(EngineerGasOpenViewActionCreator.onAction());
    } else if (res == 0) {
      await CommonUtils.showMediaAlbumView(
        ctx.context,
        initialIndex: model.imageList.indexOf(file),
        files: model.imageList,
      );
    }
  }
}

void _initState(Action action, Context<EngineerGasOpenViewState> ctx) async {
  bus.emit('updateUserPosition');

  ResultData res = await CommonNetWork.staffCheckConfig(
    worktplType: 3,
    worktplUsertype: '1',
  );
  if (res.success) {
    Map data = res.data['data'];
    String listJson = data['worktplItem'];
    List list = jsonDecode(listJson);
    List<NormalConfigModel> items = list
        .map<NormalConfigModel>((e) => NormalConfigModel.fromJson(e))
        .toList();
    ctx.state.items = items;
    ResultData detailRes =
        await CommonNetWork.fixOrderDetail(ctx.state.model.itemID);
    if (detailRes.success) {
      String dispatchLog = CommonUtils.checkNullToString(detailRes.data['data']['bizDispatchlog']);
      if (dispatchLog.isNotEmpty) {
        ctx.state.logList = jsonDecode(dispatchLog);
      }
      String jsonContent = CommonUtils.checkNullToString(
          detailRes.data['data']['bizMaintenanceremark']);
      ctx.state.remark = CommonUtils.checkNullToString(
          detailRes.data['data']['securitycheckBusinessExtend']['remark']);
      // detailRes.data['data']['']
      List info;
      print(jsonContent);
      try {
        if (jsonContent.isNotEmpty) {
          info = jsonDecode(jsonContent);
        }
      } catch (e) {
        info = null;
      }
      if (info != null) {
        List orderPhoto = CommonUtils.checkNullToString(
                    detailRes.data['data']['bizMaintenancefiles'])
                .isEmpty
            ? []
            : CommonUtils.checkNullToString(
                    detailRes.data['data']['bizMaintenancefiles'])
                .split(',');
        ctx.state.orderPhoto.addAll(orderPhoto);
        if (CommonUtils.checkNullToString(
                detailRes.data['data']['bizSignature'])
            .isNotEmpty) {
          ctx.state.signPhoto = CommonUtils.checkNullToString(
              detailRes.data['data']['bizSignature']);
        }
        for (NormalConfigModel model in ctx.state.items) {
          if (model.isRemind) {
          } else {
            model.setSaveContent(info);
          }
        }
      }
    }

    ctx.dispatch(EngineerGasOpenViewActionCreator.onAction());
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}

void _onTapPic(Action action, Context<EngineerGasOpenViewState> ctx) async {
  NormalConfigModel model = action.payload['model'];
  var file = action.payload['data'];
  int res =
      await CommonUtils.showActionSheet(ctx.context, button: ['查看', '删除']);
  if (res == 1) {
    model.imageList.remove(file);
    ctx.dispatch(EngineerGasOpenViewActionCreator.onAction());
  } else if (res == 0) {
    await CommonUtils.showMediaAlbumView(
      ctx.context,
      initialIndex: model.imageList.indexOf(file),
      files: model.imageList,
    );
  }
}

void _onTapAddPic(Action action, Context<EngineerGasOpenViewState> ctx) async {
  NormalConfigModel model = action.payload;
  AssetEntityFile imgFile = await CommonUtils.showOrderImagePicker(ctx.context,
      type: 2, info: ctx.state.model);
  if (imgFile != null) {
    model.imageList.add(imgFile);
    ctx.dispatch(EngineerGasOpenViewActionCreator.onAction());
  }
}

void _onSubmit(Action action, Context<EngineerGasOpenViewState> ctx) async {
  if (ctx.state.step == '9') {
    CommonUtils.showWaitLoading(ctx.context);
    ResultData res =
        await CommonNetWork.engineerOrderReset(ctx.state.model.itemID);
    Navigator.pop(ctx.context);
    if (res.success) {
      bus.emit('refreshList');
      await CommonUtils.showAlertView(ctx.context, '提交成功');
      Navigator.popUntil(ctx.context, ModalRoute.withName('/'));
    } else {
      CommonUtils.showErrorInfo(ctx.context, res.desc);
    }
    return;
  }
  String errStr;
  for (NormalConfigModel model in ctx.state.items) {
    if (model.valueStr.isEmpty) {
      errStr = '请选择<${model.configName}>检测内容';
      break;
    }
  }
  //
  // if (ctx.state.gasInfo.gasRemainTotalStr.length == 0) errStr = '请填写剩余气量';
  // if (ctx.state.gasInfo.gasUseTotalStr.length == 0) errStr = '请填写总用气量';
  // if (ctx.state.gasInfo.gasBuyTotalStr.length == 0) errStr = '请填写总购气量';

  if (errStr != null) {
    CommonUtils.showAlertView(ctx.context, errStr);
  } else {
    if (ctx.state.materList.isEmpty) {
      int ret = await CommonUtils.showOKCanceltView(ctx.context, '是否不添加材料信息？');
      if (ret != 1) return;
    }
    CommonUtils.pushRoute(ctx.context, RoutePath.engineerGasResultView,
        arguments: {
          'info': ctx.state.model,
          'items': ctx.state.items,
          'signPhoto': ctx.state.signPhoto,
          'orderPhotos': ctx.state.orderPhoto,
          'meterInfoModel': ctx.state.meterInfoModel,
          'materList': ctx.state.materList,
        });
  }
}
